package com.google.code.spidertr;
import java.util.List;
import java.util.Vector;

public class LinkBuilder {
	public String link;
	public String baseURI;
	private List<Pair> regPairs;

	public LinkBuilder(String link, String baseURI) {
		this.link = link;
		this.baseURI = baseURI;
		initiateRegPairs();
	}

	String getLink() {
		String tempLink = removeHtmlTag(link);
		if (validate(tempLink)) {
			return makeAbsolute();
		}
		return null;
	}

	/**
	 * Transform link to absolute uri...
	 * 
	 * @return {@link String} Absolute URI
	 */
	private String makeAbsolute() {
		if (link.matches("http://.*")) {
			return link;
		}
		return prepareLink();
	}

	/**
	 * @return
	 */
	private String prepareLink() {
		for (Pair pair : this.regPairs) {
			if (checkType(pair)) {
				return baseURI + link;
			}
		}
		throw new RuntimeException("Cannot make the link absolute. Url: "
				+ baseURI + " Link " + link);
	}

	/**
	 * @param pair
	 * @return
	 */
	private boolean checkType(Pair pair) {
		return link.matches(pair.getPre()) && baseURI.matches(pair.getPost());
	}

	/**
	 * Validate given link.
	 * 
	 * @param link
	 * @return {@link Boolean}
	 */
	private boolean validate(String link) {
		if (link.matches("javascript:.*|mailto:.*")) {
			return false;
		}
		return true;
	}

	/**
	 * Remove standart HTML Tags from given link...
	 * 
	 * @param link
	 *            {@link String}
	 * @return {@link String}
	 */
	private String removeHtmlTag(String link) {
		String tempLink = link.replaceFirst("href=\"", "").replaceFirst("\">",
				"");
		return tempLink;
	}

	/**
		 * 
		 */
	private void initiateRegPairs() {
		regPairs = new Vector<Pair>();
		regPairs.add(new Pair("/.*", ".*$[^/]"));
		regPairs.add(new Pair("/.*", ".*[/]"));
		regPairs.add(new Pair("[^/].*", ".*[^/]"));
	}
}